package keeto.com.vn.bms.utils;

import java.util.HashMap;

public class BMSCache {

	public BMSCache(int cacheSize) {
		this.cacheSize = cacheSize;
	}

	public static int CACHE_MAX_SIZE = 10;
	private int cacheSize = CACHE_MAX_SIZE;

	public HashMap<String, BMSCacheEntry> NEW_CACHE = new HashMap<String, BMSCacheEntry>();

	public HashMap<String, BMSCacheEntry> OLD_CACHE = new HashMap<String, BMSCacheEntry>();

	private final static Object LOCK_OBJ = new Object();

	public void cleanUpCache() {
		synchronized (LOCK_OBJ) {
			NEW_CACHE.values().clear();
			NEW_CACHE.clear();
			OLD_CACHE.values().clear();
			OLD_CACHE.clear();
			System.gc();
			System.runFinalization();
		}
	}

	public void cleanOutCache() {

		if (cacheSize < NEW_CACHE.size()) {

			synchronized (LOCK_OBJ) {
				OLD_CACHE.values().clear();
				OLD_CACHE.clear();
				System.gc();
				System.runFinalization();
				OLD_CACHE = NEW_CACHE;
				NEW_CACHE = new HashMap<String, BMSCacheEntry>();
			}

		}
	}

	private BMSCacheEntry getCache(String id) {
		BMSCacheEntry cache = NEW_CACHE.get(id);
		if (null == cache) {
			cache = OLD_CACHE.get(id);
		}
		return cache;
	}

	
	private void putCache(BMSCacheEntry cache) {
		synchronized (LOCK_OBJ) {
			NEW_CACHE.put(cache.id, cache);
		}
	}

	public void AddCache(BMSCacheEntry model) {

		cleanOutCache();
		putCache(model);
	}

	public BMSCacheEntry getCacheById(String id) {
		return getCache(id);
	}

	public void removeCache(String id) {
		synchronized (LOCK_OBJ) {
			if (NEW_CACHE.containsKey(id)) {
				NEW_CACHE.remove(id);
			} else if (OLD_CACHE.containsKey(id)) {
				OLD_CACHE.remove(id);
			}
		}
	}
}
